package wangjg.security.core.validator;

import java.util.Iterator;

import wangjg.security.core.ResourceFactory;
import wangjg.security.core.ResourceMatcher;




/**
 * 验证指定的[用户]是否有权限访问[请求]的资源
 * @author wangjg
 *
 */
public class RequestValidatorImpl implements RequestValidator {
	private ResourceFactory resourceFactory;
	private ResourceMatcher resourceMatcher;
	private boolean defaultAllow = true;
	private boolean checkFirst = false; //取权限的并集

	public RequestValidatorImpl() {
	}

	public boolean validate(final Object request,final Object user) {
		Iterator<?> it = this.resourceFactory.iterator();
		int matchedNum=0;
		while (it.hasNext()) {
			Object resource = it.next();
			if (resourceMatcher.match(resource, request)){
				matchedNum++;
				if(AuthorityValidator.validate(resource, user)){
					return true;
				}else if(checkFirst){
					return false;
				}
			}
		}
		//没有定义资源，则放行
		if(matchedNum==0){
			return defaultAllow;
		}
		return false;
	}

	public ResourceFactory getResourceFactory() {
		return resourceFactory;
	}

	public void setResourceFactory(ResourceFactory resourceFactory) {
		this.resourceFactory = resourceFactory;
	}

	public ResourceMatcher getResourceMatcher() {
		return resourceMatcher;
	}

	public void setResourceMatcher(ResourceMatcher resourceMatcher) {
		this.resourceMatcher = resourceMatcher;
	}

	public boolean isDefaultAllow() {
		return defaultAllow;
	}

	public void setDefaultAllow(boolean defaultAllow) {
		this.defaultAllow = defaultAllow;
	}
	
}
